<?php


namespace app\common\service;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use think\facade\Log;

class HttpService
{
    public static function get($url, $query=null)
    {
        $params=[];
        if($query){
            $params=[RequestOptions::QUERY => $query];
        }
        return self::request($url, 'GET', $params);
    }

    public static function post($url, $query)
    {
        $params=[];
        if($query){
            $params=[RequestOptions::FORM_PARAMS => $query];
        }
        return self::request($url, 'POST', $params);
    }
    public static function postJson($url, $query,$headers=null)
    {
        $params=[];
        if($query){
            $params=[RequestOptions::JSON => $query];
        }
        if($headers){
            $params_headers=[RequestOptions::HEADERS=>$headers];
            $params= array_merge($params,$params_headers);
        }
        return self::request($url, 'POST', $params);
    }
    public static function request($url, $method, $params)
    {
        try {
            $client = new Client(['verify' => false]);
            $res = $client->request($method, $url, $params);
        } catch (GuzzleException $e) {
//            self::log($e->getMessage(),$url,$params);
            return self::getError($e->getMessage());
        }
        $result = json_decode($res->getBody()->getContents(), true);
        self::log($result,$url,$params);

        return self::getSuccess($result);

    }
    private static function log($msg, $url,$params)
    {
        Log::record(['msg'=>$msg,'url'=>$url,'params'=>$params]);
    }
    public static function getSuccess($data = '', $msg = 'success')
    {
        return self::getResult($data, 1, $msg);
    }

    public static function getError($msg = '', $data = '')
    {
        return self::getResult($data, 0, $msg);
    }

    private static function getResult($data, $code = 0, $msg = '')
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];
    }
    public static function isSuccess($data)
    {
        return $data['code'] == 1;
    }

    public static function getData($res)
    {
        return $res['data'];
    }
    public static function getMsg($res)
    {
        return $res['msg'];
    }

    /**
     * 日志
     * @param string $title
     * @param mixed $msg
     * @return void
     */
    public static function logInfo(string $title,  $msg=[])
    {
        if(empty($msg)){
            $msg=[];
        }
        Log::record([
            '__title__'=>$title
        ]+$msg);
    }
}
